package cn.bookcycle.panda.userweb.controller;
import cn.bookcycle.panda.userweb.pojo.vo.UserVO;
import cn.bookcycle.panda.userweb.constant.URLConstant;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.security.token.SSOToken;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 * @author Mason
 * @date 2018/3/6
 */
@Controller
public class UserController extends BaseController{
    protected Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/showUser",method = RequestMethod.GET)
    public String ShowUser( Model model){
        SSOToken ssoToken=SSOHelper.getSSOToken(request);
        String userId=ssoToken.getId();
        RestTemplate restTemplate=new RestTemplate();
        try{
            ResponseEntity<Object> responseEntity=restTemplate.getForEntity(URLConstant.GET_USER_BY_USERID+userId,Object.class);
            Object user=responseEntity.getBody();
            JSONObject jsonObject=JSONObject.fromObject(user);
            UserVO userVO=new UserVO();


            if(jsonObject.containsKey("address")){
                userVO.setAddress(jsonObject.get("address").toString());
            }
            if(jsonObject.containsKey("avatar")){
                userVO.setAvatar(jsonObject.get("avatar").toString());
            }
            if(jsonObject.containsKey("nickname")){
                userVO.setNickname(jsonObject.get("nickname").toString());
            }
            if(jsonObject.containsKey("sex")){
               userVO.setSex(jsonObject.get("sex").toString());
            }
//            if(jsonObject.containsKey("birthday")){
//                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
//                Object object=jsonObject.get("birthday");
//                Date birthday=new Date(Long.parseLong(object.toString()));
//                userVO.setBirthday(sdf.format(birthday));
//            }
            model.addAttribute("userVO",userVO);
            return "user";
        }catch (HttpClientErrorException e){
            return "error";
        }
    }

    /**
     *
     * @param avatar
     * @return
     */
    @RequestMapping(value = "/updateAvatar" ,method = RequestMethod.POST)
    public String updateAvatar(@RequestParam("avatar")MultipartFile avatar){
        String userId=SSOHelper.getSSOToken(request).getId();
        try{
            if(!"".equals(avatar.getOriginalFilename())){
                File result=new File(userId+".jpg");
                FileOutputStream fileOutputStream=new FileOutputStream(result);
                fileOutputStream.write(avatar.getBytes());
                fileOutputStream.flush();
                fileOutputStream.close();
                FileSystemResource fileSystemResource=new FileSystemResource(result);
                MultiValueMap param1=new LinkedMultiValueMap();
                param1.add("file",fileSystemResource);
                param1.add("filepath","/images/avatar");
                RestTemplate restTemplate=new RestTemplate();
                ResponseEntity<String> imgEntity=restTemplate.postForEntity(URLConstant.URL_UPLOAD_FILE,param1,String.class);
                ResponseEntity<Object> ruserEntity=restTemplate.getForEntity(URLConstant.GET_USER_BY_USERID+userId,Object.class);
                JSONObject jsonUser=JSONObject.fromObject(ruserEntity.getBody());
                String avatarStr=imgEntity.getBody();
                jsonUser.element("avatar",avatarStr);
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                HttpEntity entity=new HttpEntity(jsonUser.toString(),headers);
                result.delete();
                restTemplate.exchange(URLConstant.UPDATE_USER, HttpMethod.PUT,entity,String.class);

            }
            return redirectTo("showUser");
        }catch (IOException ioe){
            return "";
        }catch (HttpClientErrorException hce){
            return "";
        }
    }

    /**
     *
     * @param sex
     * @param birthday
     * @param nickname
     * @param address
     * @return
     */
    @RequestMapping(value = "/updateUser" ,method = RequestMethod.POST)
    public String updateUser(@Nullable@RequestParam("sex")String sex,
                           @Nullable@RequestParam("birthday")String birthday,
                           @Nullable@RequestParam("nickname")String nickname,
                           @Nullable@RequestParam("address")String address){
        String userId=SSOHelper.getSSOToken(request).getId();
        RestTemplate restTemplate=new RestTemplate();
        ResponseEntity<Object> responseUser=restTemplate.getForEntity(URLConstant.GET_USER_BY_USERID+userId,Object.class);
        JSONObject jsonUser=JSONObject.fromObject(responseUser.getBody());
        jsonUser.element("sex",sex);

        if(birthday!=null){
            try {
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                Date date=sdf.parse(birthday);
                jsonUser.element("birthday",date.getTime());
            }catch (ParseException e){
                e.getStackTrace();
            }
        }
        if(nickname!=null){
            jsonUser.element("nickname",nickname);
        }
        if(address!=null){
            jsonUser.element("address",address);
        }

        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
            HttpEntity entity=new HttpEntity(jsonUser.toString(),headers);
            restTemplate.exchange(URLConstant.UPDATE_USER, HttpMethod.PUT,entity,String.class);
            return redirectTo("showUser");
        }catch (HttpClientErrorException e){
            return "error";
        }
    }

    /**
     * 获取缓存Cookie中的用户ID
     * @return
     */
    @RequestMapping(value = "/getUserId")
    @ResponseBody
    public String getUserId(){
        SSOToken ssoToken=SSOHelper.getSSOToken(request);
        if(ssoToken!=null){
            return ssoToken.getId();
        }else {
            return "please login first";
        }
    }
}
